import * as XLSX from "xlsx"


export function exportExcel(json, name, titleArr, sheetName) {
  /* convert state to workbook */
  const data = new Array();
  const keyArray = new Array();
  const getLength = function (obj) {
    let count = 0;
    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        count++;
      }
    }
    return count;
  };
  for (const key1 in json) {
    if (json.hasOwnProperty(key1)) {
      const element = {
        code:json[key1].code,
        goodsName:json[key1].goodsName,
        inventory:json[key1].inventory,
        cost:json[key1].cost,
        price:json[key1].price,
        warn:json[key1].warn
      };
      var rowDataArray = new Array();
      for (const key2 in element) {
        if (element.hasOwnProperty(key2)) {
          const element2 = element[key2]
          rowDataArray.push(element2);
          if (keyArray.length < getLength(element)&&key2!=="storeId"&&key2!=="goodsType"&&key2!=="image"
              &&key2!=="recentSales"&&key2!=="creationDate"&&key2!=="state") {
            keyArray.push(key2);
          }
        }
      }
      data.push(rowDataArray);
    }
  }
  // keyArray为英文字段表头
  data.splice(0, 0,  titleArr);
  console.log('data', data);
  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  // 此处隐藏英文字段表头
  var wsrows = [{ hidden: true }];
  ws['!rows'] = wsrows; // ws - worksheet
  XLSX.utils.book_append_sheet(wb, ws, sheetName);
  /* generate file and send to client */
  XLSX.writeFile(wb, name + '.xlsx');
}
